package com.ricervcvcer.order.controller;


import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ricervcvcer.order.client.GoodsClient;
import com.ricervcvcer.order.dto.OrderDto;
import com.ricervcvcer.order.entity.OrderDetailEntity;
import com.ricervcvcer.order.entity.OrderEntity;
import com.ricervcvcer.order.entity.TbSku;
import com.ricervcvcer.order.entity.TbStock;
import com.ricervcvcer.order.service.OrderService;
import com.ricervcvcer.order.util.PageUtils;
import com.ricervcvcer.order.util.R;
import com.ricervcvcer.order.vo.OrderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-06
 */
@RestController
@RequestMapping("order")
public class TbOrderController {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private OrderService orderService;

    // 小的资源访问权限（permis）
    @PostMapping("create")
    public OrderVo createOrder(@RequestBody List<OrderDto> orderDtos){
        OrderVo orderVo = new OrderVo();
        List<OrderDetailEntity> details = new ArrayList<>();
        Long totalPay = 0L;
        // 产生一个订单对象和多个订单详情对象
        for (OrderDto orderDto : orderDtos) {
            // 首先根据编号获得商品信息
            Long id = orderDto.getId();
            TbSku sku = goodsClient.getSkuById(id);
            // 判断库存是否充足
            Integer count = orderDto.getCount();
            TbStock stock = goodsClient.getStockById(id);
            if(count > stock.getStock()){
                return null;
            }
            // 创建订单详情
            OrderDetailEntity detail = new OrderDetailEntity();
            detail.setSkuId(id);
            detail.setPrice(sku.getPrice());
            detail.setNum(count);

            // 添加到详情集合中
            details.add(detail);

            // 计算出每一个商品购买N件的价格
            totalPay += sku.getPrice() * count;
        }
        OrderEntity order = new OrderEntity();
        order.setTotalPay(totalPay);
        order.setCreateTime(new Date());
        // 插入数据库

        //模拟一次网络延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 返回给前端
        BeanUtils.copyProperties(order, orderVo);
        orderVo.setDetails(details);
        return orderVo;
    }

    @RequestMapping("message7")
    public String message7(HttpServletRequest request) {;
        String token = request.getHeader("jwt-token");
        String decode = Base64.decodeStr(token);
        Object parse = JSON.parse(decode);
        JSONObject jsonObject = parse != null ? (JSONObject) parse : null;
        String principal = (String) jsonObject.get("principal");
        String userDTO = Base64.decodeStr(principal);
        System.out.println(userDTO);
        return "message7";
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{orderId}")
    public R info(@PathVariable("orderId") Long orderId){
        OrderEntity order = orderService.getById(orderId);
        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order){
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderEntity order){
        orderService.updateById(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] orderIds){
        orderService.removeByIds(Arrays.asList(orderIds));

        return R.ok();
    }
}
